﻿/*
* CRM_order.cs
*
* 功 能： N/A
* 类 名： CRM_order
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Web;
using System.Web.Script.Serialization;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class CRM_order
    {
        public static BLL.CRM_order order = new BLL.CRM_order();
        public static Model.CRM_order model = new Model.CRM_order();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public CRM_order()
        {
        }

        public CRM_order(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public void save()
        {
            model.Customer_id = int.Parse(request["T_Customer_val"]);

            model.Order_date = DateTime.Parse(request["T_date"]);
            model.pay_type_id = int.Parse(request["T_paytype_val"]);
            model.Order_details = PageValidate.InputText(request["T_details"], 4000);
            model.Order_status_id = int.Parse(request["T_status_val"]);
            model.Order_amount = decimal.Parse(request["T_amount"]);

            

            model.C_dep_id = int.Parse(request["c_dep_val"]);
            model.C_emp_id = int.Parse(request["c_emp_val"]);

            model.F_dep_id = int.Parse(request["f_dep_val"]);
            model.F_emp_id = int.Parse(request["f_emp_val"]);

            int orderid;
            string pid = PageValidate.InputText(request["orderid"], 50);
            if (PageValidate.IsNumber(pid))
            {
                model.id = int.Parse(pid);
                DataSet ds = order.GetList("id=" + model.id);
                DataRow dr = ds.Tables[0].Rows[0];
                orderid = model.id;

                order.Update(model);
                //context.Response.Write(model.id );


                var log = new sys_log();
                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = dr["Customer_name"].ToString();
                string EventType = "订单修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["Customer_name"].ToString() != request["T_Customer"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "客户", dr["Customer_name"], request["T_Customer"]);

                if (dr["Order_details"].ToString() != request["T_details"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "订单详情", dr["Order_details"], request["T_details"]);

                if (DateTime.Parse(dr["Order_date"].ToString()) != DateTime.Parse(request["T_date"]))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "成交时间", dr["Order_date"], request["T_date"]);

                if (dr["Order_amount"].ToString() != request["T_amount"].Replace(",", "").Replace(".00", ""))
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "订单总额", dr["Order_amount"],
                        request["T_amount"].Replace(",", "").Replace(".00", ""));

                if (dr["Order_status"].ToString() != request["T_status"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "订单状态", dr["Order_status"], request["T_status"]);

                if (dr["F_dep_name"].ToString() != request["f_dep"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "促成人员部门", dr["F_dep_name"], request["f_dep"]);

                if (dr["F_emp_name"].ToString() != request["f_emp"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "促成人员", dr["F_emp_name"], request["f_emp"]);

                if (dr["pay_type"].ToString() != request["T_paytype"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "支付方式", dr["pay_type"], request["T_paytype"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.create_id = emp_id;
                model.create_date = DateTime.Now;

                model.isDelete = 0;
                model.Serialnumber = DateTime.Now.AddMilliseconds(3).ToString("yyyyMMddHHmmssfff").Trim();
                //model.arrears_invoice = decimal.Parse(request["T_amount"]);
                orderid = order.Add(model);
            }
            //更新订单收款金额
            order.UpdateReceive(orderid);
            //更新订单发票金额
            order.UpdateInvoice(orderid);
            //customerid
            order.UpdateCustomerID(orderid, int.Parse(request["T_Customer_val"]));

            string json = request["PostData"].ToLower();
            var js = new JavaScriptSerializer();

            PostData[] postdata;
            postdata = js.Deserialize<PostData[]>(json);

            var cod = new BLL.CRM_order_details();
            var modeldel = new Model.CRM_order_details();

            modeldel.order_id = orderid;
            cod.Delete(" order_id=" + modeldel.order_id);
            for (int i = 0; i < postdata.Length; i++)
            {
                modeldel.product_id = postdata[i].Product_id;
                modeldel.product_name = postdata[i].Product_name;
                modeldel.quantity = postdata[i].Quantity;
                modeldel.unit = postdata[i].Unit;
                modeldel.price = postdata[i].Price;
                modeldel.amount = postdata[i].Amount;

                cod.Add(modeldel);
            }
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " id";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = "1=1";
            string issar = request["issarr"];
            if (issar == "1")
            {
                serchtxt += " and isnull( arrears_money,0)>0";
            }


            if (!string.IsNullOrEmpty(request["company"]))
                serchtxt += $" and Customer_id in (select id from CRM_Customer where Customer like N'%{ PageValidate.InputText(request["company"], 255)}%')";

            if (!string.IsNullOrEmpty(request["contact"]))
                serchtxt += " and Order_status_id = " + int.Parse(request["contact_val"]);

            if (!string.IsNullOrEmpty(request["department"]))
                serchtxt += " and F_dep_id = " + int.Parse(request["department_val"]);

            if (!string.IsNullOrEmpty(request["employee"]))
                serchtxt += " and F_emp_id = " + int.Parse(request["employee_val"]);

            if (!string.IsNullOrEmpty(request["startdate"]))
                serchtxt += " and Order_date >= '" + PageValidate.InputText(request["startdate"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate"]);
                serchtxt += " and Order_date <= '" +
                            DateTime.Parse(request["enddate"]).AddHours(23).AddMinutes(59).AddSeconds(59) + "'";
            }

            if (!string.IsNullOrEmpty(request["startdate_del"]))
                serchtxt += " and Delete_time >= '" + PageValidate.InputText(request["startdate_del"], 255) + "'";

            if (!string.IsNullOrEmpty(request["enddate_del"]))
            {
                DateTime enddate = DateTime.Parse(request["enddate_del"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and Delete_time <= '" + enddate + "'";
            }

            //权限 
            serchtxt += DataAuth();
            DataSet ds = order.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);
        }

        public string gridbycustomerid(int customerid)
        {
            DataSet ds = order.GetList(0, " Customer_id =" + customerid, " Order_date desc");
            return (GetGridJSON.DataTableToJSON(ds.Tables[0]));
        }

        public string form(string id)
        {
            string dt;
            if (PageValidate.IsNumber(id))
            {
                DataSet ds = order.GetList("id= " + id);
                dt = DataToJson.DataToJSON(ds);
            }
            else
            {
                dt = "{}";
            }
            return (dt);
        }

        public string del(int id)
        {
            DataSet ds = order.GetList("id=" + id);

            var contract = new BLL.CRM_contract();
            var invoice = new BLL.CRM_invoice();
            var receive = new BLL.CRM_receive();
            if (invoice.GetList("order_id=" + id).Tables[0].Rows.Count > 0)
            {
                //invoice
                return ("false:invoice");
            }
            if (receive.GetList("order_id=" + id).Tables[0].Rows.Count > 0)
            {
                //receive
                return ("false:receive");
            }
            bool canedel = true;
            if (uid != "admin")
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid("3", "Sys_del", emp_id);

                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "none":
                        canedel = false;
                        break;
                    case "my":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["C_emp_id"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "dep":
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            if (ds.Tables[0].Rows[i]["C_dep_id"].ToString() == arr[1])
                                canedel = true;
                            else
                                canedel = false;
                        }
                        break;
                    case "all":
                        canedel = true;
                        break;
                }
            }
            if (canedel)
            {
                bool isdel = order.Delete(id);
                var cod = new BLL.CRM_order_details();
                cod.Delete("order_id=" + id);

                if (isdel)
                {
                    //日志
                    string EventType = "订单删除";

                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    int EventID = id;
                    string EventTitle = ds.Tables[0].Rows[0]["Customer_name"].ToString();

                    var log = new sys_log();

                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

                    return ("true");
                }
                return ("false");
            }
            return ("delfalse");
        }

        private string DataAuth()
        {
            //权限            
            string uid = employee.uid;
            string returntxt = "";

            if (uid != "admin")
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid("3", "Sys_view", emp_id);

                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "none":
                        returntxt = " and 1=2 ";
                        break;
                    case "my":
                        returntxt = " and  C_emp_id=" + arr[1];
                        break;
                    case "dep":
                        if (string.IsNullOrEmpty(arr[1]))
                            returntxt = " and  C_emp_id=" + int.Parse(uid);
                        else
                            returntxt = " and  C_dep_id=" + arr[1];
                        break;
                    case "depall":
                        var dep = new BLL.hr_department();
                        DataSet ds = dep.GetAllList();
                        string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), ds.Tables[0]);
                        string intext = arr[1] + "," + deptask;
                        returntxt = " and  C_dep_id in (" + intext.TrimEnd(',') + ")";
                        break;
                }
            }

            return returntxt;
        }

        public class PostData
        {
            public int? Product_id { get; set; }

            public string Product_name { get; set; }

            public decimal? Price { get; set; }

            public int? Quantity { get; set; }

            public string Unit { get; set; }

            public decimal? Amount { get; set; }
        }
    }
}